package com.oj.judge.config;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.netty.NettyDockerCmdExecFactory;
import com.oj.judge.domain.DockerSandBoxPool;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

/**
 * @Description
 * @Author bin
 * @Date 2025/7/1
 */
@RefreshScope
@Configuration
public class DockerSandBoxPoolConfig {

    @Value("${sandbox.docker.host:tcp://localhost:2375}")
    private String dockerHost;

    @Value("${sandbox.limit.memory:100000000}")
    private Long memoryLimit;

    @Value("${sandbox.limit.memory-swap:100000000}")
    private Long memorySwapLimit;

    @Value("${sandbox.limit.cpu:1}")
    private Long cpuLimit;

    @Value("${sandbox.limit.time:5}")
    private Long timeLimit;

    @Value("${sandbox.docker.image:openjdk:8-jdk-alpine}")
    private String sandboxImage; // 容器镜像

    @Value("${sandbox.docker.volume:/usr/share/java}")
    private String volumeDir; // 挂载路径

    @Value("${sandbox.docker.pool.size:4}")
    private int poolSize;

    @Value("${sandbox.docker.name-prefix:oj-sandbox-jdk}")
    private String containerNamePrefix;

    private DockerClient dockerClient;

    @Bean
    public DockerClient dockerClient_user() {

        DefaultDockerClientConfig clientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost(dockerHost)
                .build();
        dockerClient = DockerClientBuilder
                .getInstance(clientConfig)
                .withDockerCmdExecFactory(new NettyDockerCmdExecFactory())
                .build();
        return dockerClient;
    }

    @Bean
    @DependsOn("dockerClient_user")
    public DockerSandBoxPool createDockerSandBoxPool() {
        if(dockerClient == null){
            System.out.println("dockerClient == null");
        } else {
            System.out.println("dockerClient != null");
        }
        // 创建容器池
        DockerSandBoxPool dockerSandBoxPool = new DockerSandBoxPool(dockerClient, sandboxImage, volumeDir, containerNamePrefix, memoryLimit, memorySwapLimit, cpuLimit, timeLimit, poolSize);
        dockerSandBoxPool.initDockerPool(poolSize);
        return dockerSandBoxPool;
    }
}
